﻿using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Duellum.Map.WPFTest
{
	#if DEBUG
	static class ImageHelper
	{
		static public void MakeTransparentBitmap(Uri source, string destination)
		{
			BitmapSource image = new BitmapImage(source);
			image = MakeTransparentBitmap(image, Color.FromRgb(0xFF, 0xFF, 0xFF));
			
			if (!Path.IsPathRooted(destination)) {
				destination = Path.Combine(Environment.CurrentDirectory, destination);
			}
			
			var enc = new GifBitmapEncoder();
			enc.Frames.Add(BitmapFrame.Create(image));
			using (var file = new FileStream(destination, FileMode.CreateNew))
			{
				enc.Save(file);
			}
		}
		
		static public BitmapSource MakeTransparentBitmap(BitmapSource sourceImage, Color transparentColor)
		{
			if (sourceImage.Format != PixelFormats.Bgra32) //if input is not ARGB format convert to ARGB firstly
			{
				sourceImage = new FormatConvertedBitmap(sourceImage, PixelFormats.Bgra32, null, 0.0);
			}

			int stride = (sourceImage.PixelWidth * sourceImage.Format.BitsPerPixel) / 8;

			byte[] pixels = new byte[sourceImage.PixelHeight * stride];

			sourceImage.CopyPixels(pixels, stride, 0);

			byte red = transparentColor.R;
			byte green = transparentColor.G;
			byte blue = transparentColor.B;
			for (int i = 0; i < sourceImage.PixelHeight * stride; i += (sourceImage.Format.BitsPerPixel / 8))
			{

				// set transparency color

				if (pixels[ i ]==blue
				&& pixels[i + 1]==green
				&& pixels[i + 2]==red)
				{
					pixels[i + 3] = 0;
				}

			}

			BitmapSource newImage
			= BitmapSource.Create(sourceImage.PixelWidth, sourceImage.PixelHeight,
				sourceImage.DpiX, sourceImage.DpiY, PixelFormats.Bgra32, sourceImage.Palette, pixels, stride);

			return newImage;
		}
	}
	#endif
}
